package com.example.qu_tao.adapter;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.qu_tao.R;
import com.example.qu_tao.entity.Post;
import com.example.qu_tao.database.DBHelper;

import java.util.ArrayList;
import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

    private Context context;
    private List<Post> postList;
    private OnItemClickListener onItemClickListener;
    private int COLOR_LIKED; // 点赞时的颜色
    private int COLOR_UNLIKED; // 未点赞时的颜色
    private int IMAGE_LIKED; // 点赞时的图片资源
    private int IMAGE_UNLIKED; // 未点赞时的图片资源

    public PostAdapter(Context context, List<Post> postList) {
        this.context = context;
        this.postList = postList;
        this.COLOR_LIKED = ContextCompat.getColor(context, R.color.liked_color);
        this.COLOR_UNLIKED = ContextCompat.getColor(context, R.color.unliked_color);
        this.IMAGE_LIKED = R.mipmap.dianzan_selected;
        this.IMAGE_UNLIKED = R.mipmap.dianzan_normal;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Post post = postList.get(position);
        holder.tvUsername.setText(post.getUsername());
        holder.tvContent.setText(post.getContent());
        holder.tvTime.setText(post.getCreateTime());
        holder.tvLikeCount.setText(String.valueOf(post.getLikeCount()));

        // 根据点赞状态设置点赞图片和点赞数文本颜色
        if (post.isLiked()) {
            holder.ivLike.setImageResource(IMAGE_LIKED);
            holder.tvLikeCount.setTextColor(COLOR_LIKED);
        } else {
            holder.ivLike.setImageResource(IMAGE_UNLIKED);
            holder.tvLikeCount.setTextColor(COLOR_UNLIKED);
        }

        // 设置关注按钮文本
        if (isFollowed(post.getUserId())) {
            holder.tvFollow.setText("你关注的");
        } else {
            holder.tvFollow.setText("关注");
        }

        // 设置关注按钮点击事件
        holder.tvFollow.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onFollowClick(post, holder.tvFollow);
                // 更新所有相同用户的关注状态
                updateFollowStatusForUser(post.getUserId());
            }
        });

        // 设置点赞和评论点击事件
        holder.ivLike.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onLikeClick(post);
                post.setLiked(!post.isLiked()); // 切换点赞状态
                if (post.isLiked()) {
                    post.setLikeCount(post.getLikeCount() + 1); // 点赞数加 1
                } else {
                    post.setLikeCount(post.getLikeCount() - 1); // 取消点赞，点赞数减 1
                }
                holder.tvLikeCount.setText(String.valueOf(post.getLikeCount()));

                // 根据新的点赞状态更新点赞图片和点赞数文本颜色
                if (post.isLiked()) {
                    holder.ivLike.setImageResource(IMAGE_LIKED);
                    holder.tvLikeCount.setTextColor(COLOR_LIKED);
                } else {
                    holder.ivLike.setImageResource(IMAGE_UNLIKED);
                    holder.tvLikeCount.setTextColor(COLOR_UNLIKED);
                }
            }
        });

        // 显示图片
        if (post.getImages() != null && !post.getImages().isEmpty()) {
            List<Bitmap> bitmaps = new ArrayList<>();
            for (byte[] imageData : post.getImages()) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                bitmaps.add(bitmap);
            }
            ImageAdapter imageAdapter = new ImageAdapter(context, bitmaps);
            holder.recyclerImages.setLayoutManager(new GridLayoutManager(context, 3));
            holder.recyclerImages.setAdapter(imageAdapter);
        } else {
            // 没有图片时，清空 RecyclerView 的内容
            holder.recyclerImages.setLayoutManager(null);
            holder.recyclerImages.setAdapter(null);
        }
    }

    @Override
    public int getItemCount() {
        return postList.size();
    }

    private boolean isFollowed(int userId) {
        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String query = "SELECT * FROM follow WHERE user_id = ? AND followed_user_id = ?";
        Cursor cursor = db.rawQuery(query, new String[]{"1", String.valueOf(userId)});
        boolean isFollowed = cursor.getCount() > 0;
        cursor.close();
        db.close();
        return isFollowed;
    }

    private void updateFollowStatusForUser(int userId) {
        boolean isNowFollowed = isFollowed(userId);
        for (int i = 0; i < postList.size(); i++) {
            if (postList.get(i).getUserId() == userId) {
                notifyItemChanged(i);
            }
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        RecyclerView recyclerImages;
        ImageView ivAvatar;
        TextView tvUsername;
        TextView tvTime;
        TextView tvContent;
        ImageView ivLike;
        TextView tvLikeCount;
        TextView tvFollow;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            recyclerImages = itemView.findViewById(R.id.recycler_images);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
            tvUsername = itemView.findViewById(R.id.tv_username);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvContent = itemView.findViewById(R.id.tv_content);
            ivLike = itemView.findViewById(R.id.iv_like);
            tvLikeCount = itemView.findViewById(R.id.tv_like_count);
            tvFollow = itemView.findViewById(R.id.tv_follow);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(Post post);
        void onLikeClick(Post post);
        void onFollowClick(Post post, TextView followButton);
    }
}